<?php
declare (strict_types = 1);

namespace app\model;

use app\BaseModel;

/**
 * User模型
 */
class User extends BaseModel
{
    // 设置表名
    protected $name = 'users';
    
    // 设置字段信息
    protected $schema = [
        'id'               => 'int',
        'openid'           => 'string',
        'nickname'         => 'string',
        'avatar'           => 'string',
        'gender'           => 'int',
        'age'              => 'int',
        'city'             => 'string',
        'wechat_id'        => 'string',
        'wechat_qrcode'    => 'string',
        'balance'          => 'float',
        'agent_level'      => 'int',
        'parent_id'        => 'int',
        'commission'       => 'float',
        'team_commission'  => 'float',
        'team_count'       => 'int',
        'level_update_time' => 'datetime',
        'status'           => 'int',
        'create_time'      => 'datetime',
        'update_time'      => 'datetime',
    ];
    
    // 设置自动时间戳
    protected $autoWriteTimestamp = true;
    
    // 关闭软删除
    protected $deleteTime = false;
    
    /**
     * 获取用户等级文本
     */
    public function getLevelTextAttr()
    {
        $levels = [1 => 'V1', 2 => 'V2', 3 => 'V3'];
        return $levels[$this->agent_level] ?? 'V1';
    }
    
    /**
     * 获取性别文本
     */
    public function getGenderTextAttr()
    {
        $genders = [0 => '未知', 1 => '男', 2 => '女'];
        return $genders[$this->gender] ?? '未知';
    }
    
    /**
     * 获取用户的下级用户列表
     */
    public function children()
    {
        return $this->hasMany(User::class, 'parent_id', 'id');
    }
    
    /**
     * 获取用户的直接上级
     */
    public function parent()
    {
        return $this->belongsTo(User::class, 'parent_id', 'id');
    }
    
    /**
     * 获取用户的所有投递的纸条
     */
    public function notes()
    {
        return $this->hasMany(Note::class, 'user_id', 'id');
    }
    
    /**
     * 获取用户的所有抽取记录
     */
    public function draws()
    {
        return $this->hasMany(NoteDraw::class, 'user_id', 'id');
    }
    
    /**
     * 获取用户的佣金记录
     */
    public function commissions()
    {
        return $this->hasMany(CommissionRecord::class, 'user_id', 'id');
    }
    
    /**
     * 获取用户的最顶级上级ID
     *
     * @return int 顶级上级ID，如果没有上级则返回自己的ID
     */
    public function getTopParentId()
    {
        if ($this->parent_id == 0) {
            return $this->id;
        }
        
        $parentId = $this->parent_id;
        $parentIds = [$parentId];
        
        // 最多查找10层，防止无限循环
        for ($i = 0; $i < 10; $i++) {
            $parent = self::where('id', $parentId)->find();
            if (!$parent || $parent->parent_id == 0) {
                return $parentId;
            }
            
            $parentId = $parent->parent_id;
            
            // 检测循环引用
            if (in_array($parentId, $parentIds)) {
                return $this->id; // 如果检测到循环引用，返回自己的ID
            }
            
            $parentIds[] = $parentId;
        }
        
        return $parentId;
    }
    
    /**
     * 检查并执行自动升级
     */
    public function checkAndAutoUpgrade()
    {
        // 已经是最高级别
        if ($this->agent_level >= 3) {
            return false;
        }
        
        $nextLevel = $this->agent_level + 1;
        $canUpgrade = false;
        
        // 从系统设置中获取升级条件参数
        $settings = \app\model\SystemSetting::getSettings();
        
        // 检查升级条件
        if ($nextLevel == 2) {
            // 升级到V2的条件检查
            $teamCountTarget = floatval($settings['v2_upgrade_team_count'] ?? 15);
            $teamCommissionTarget = floatval($settings['v2_upgrade_team_commission'] ?? 500);
            $personalCommissionTarget = floatval($settings['v2_upgrade_personal_commission'] ?? 5000);
            $minCommission = floatval($settings['v2_upgrade_min_commission'] ?? 10);
            
            $teamCommissionCount = \app\model\CommissionRecord::alias('cr')
                ->join('users u', 'cr.from_user_id = u.id')
                ->where('u.parent_id', $this->id)
                ->where('cr.amount', '>', $minCommission)
                ->count();
                
            $teamCommission = $this->team_commission;
            $personalCommission = $this->commission;
            
            // 满足任一条件即可升级
            $canUpgrade = $teamCommissionCount >= $teamCountTarget || 
                         $teamCommission >= $teamCommissionTarget || 
                         $personalCommission >= $personalCommissionTarget;
                         
            // 记录升级判断过程
            \think\facade\Log::info("升级V2检查 - 用户ID：{$this->id}，团队下级数量：{$teamCommissionCount}/{$teamCountTarget}，团队佣金：{$teamCommission}/{$teamCommissionTarget}，个人佣金：{$personalCommission}/{$personalCommissionTarget}，结果：" . ($canUpgrade ? '可升级' : '不可升级'));
                         
        } else if ($nextLevel == 3) {
            // 升级到V3的条件检查
            $teamCountTarget = floatval($settings['v3_upgrade_team_count'] ?? 180);
            $teamCommissionTarget = floatval($settings['v3_upgrade_team_commission'] ?? 18000);
            $personalCommissionTarget = floatval($settings['v3_upgrade_personal_commission'] ?? 25000);
            $minCommission = floatval($settings['v3_upgrade_min_commission'] ?? 10);
            
            $teamCommissionCount = \app\model\CommissionRecord::alias('cr')
                ->join('users u', 'cr.from_user_id = u.id')
                ->where('u.parent_id', $this->id)
                ->where('cr.amount', '>', $minCommission)
                ->count();
                
            $teamCommission = $this->team_commission;
            $personalCommission = $this->commission;
            
            // 满足任一条件即可升级
            $canUpgrade = $teamCommissionCount >= $teamCountTarget || 
                         $teamCommission >= $teamCommissionTarget || 
                         $personalCommission >= $personalCommissionTarget;
                         
            // 记录升级判断过程
            \think\facade\Log::info("升级V3检查 - 用户ID：{$this->id}，团队下级数量：{$teamCommissionCount}/{$teamCountTarget}，团队佣金：{$teamCommission}/{$teamCommissionTarget}，个人佣金：{$personalCommission}/{$personalCommissionTarget}，结果：" . ($canUpgrade ? '可升级' : '不可升级'));
        }
        
        // 如果可以升级，执行升级
        if ($canUpgrade) {
            try {
                $this->save([
                    'agent_level' => $nextLevel,
                    'level_update_time' => date('Y-m-d H:i:s')
                ]);
                
                // 记录升级日志
                \think\facade\Log::info("用户自动升级成功 - 用户ID：{$this->id}，新等级：V{$nextLevel}");
                
                // TODO: 可以在这里添加升级通知逻辑
                // 例如：发送系统消息、微信模板消息等
                
                return true;
            } catch (\Exception $e) {
                \think\facade\Log::error("用户自动升级失败 - 用户ID：{$this->id}，错误：" . $e->getMessage());
                return false;
            }
        }
        
        return false;
    }
} 